<template>
  <el-dialog :model-value="modelValue" @close="close()" draggable :title="title" width="50%">
    <el-form :model="form" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="userName">
            <el-input placeholder="姓名" v-model="form.userName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="昵称" prop="nickName">
            <el-input placeholder="昵称" v-model="form.nickName" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input placeholder="邮箱" v-model="form.email" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电话" prop="phone">
            <el-input placeholder="电话" v-model="form.phone" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="启用" prop="enabled">
            <el-switch v-model="form.isEnabled" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="内置管理员" prop="isAdmin">
            <el-switch v-model="form.isAdmin" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close()">取消</el-button>
        <el-button type="primary" @click="saveForm()">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import UserApi, { EditUser } from "@/api/sys/user/index";
import { EditEnum } from "@/enums/EditEnum";

const props = defineProps({
  modelValue: Boolean,
  info: Object,
  type: Number,
  title: String,
});

const form = ref<EditUser>();
watch(
  () => props.info,
  (newInfo: EditUser, oldInfo: EditUser) => {
    if (newInfo) {
      form.value = newInfo;
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

const emits = defineEmits(["update:modelValue", "success"]);
const saveForm = async () => {
  const { success, message } = await UserApi[EditEnum[props.type]](form.value);
  if (success) {
    emits("success");
    ElNotification({
      title: message,
      type: "success",
    });
    close();
  } else {
    ElNotification({
      title: message,
      type: "error",
    });
  }
};

const close = () => {
  emits("update:modelValue");
};
</script>
@/api/sys/user/index
